package cn.djun.news.service.impl;

import cn.djun.news.dao.NewsDao;
import cn.djun.news.entity.News;
import cn.djun.news.entity.User;
import cn.djun.news.service.NewsService;
import cn.djun.news.util.Paginating;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author djun
 * @classname NewsServiceImpl
 * @description
 * @date 2020/11/24 14:40
 * @email 3170495286@qq.com
 */
@Service
@Slf4j
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsDao newsDao;

    /**
     * 根据新闻标题查询新闻
     *
     * @param title
     * @return
     */
    @Override
    public boolean isNewsName(String title) {
        try {
            News news = newsDao.getNewsByName(title);
            if (news != null) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 随机查询4条新闻
     * @param news
     * @return
     */
    @Override
    public Paginating<News> getfourList(News news) {
        try {
            PageHelper.startPage(news.getPageNum(), news.getPageSize());
            List<News> list = newsDao.getfourList(news);
            PageInfo<News> p = new PageInfo<>(list);
            return new Paginating<>(p);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 添加新闻
     *
     * @param news
     * @return
     */
    @Override
    public int addNews(News news) {
        try {
            return newsDao.insertNews(news);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 分页查询新闻
     *
     * @param news
     * @return
     */
    @Override
    public Paginating<News> getNewsList(News news) {
        try {
            PageHelper.startPage(news.getPageNum(), news.getPageSize());
            List<News> list = newsDao.getNewsList(news);
            PageInfo<News> p = new PageInfo<>(list);
            return new Paginating<>(p);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * 修改新闻
     *
     * @param news
     * @return
     */
    @Override
    public int updata(News news) {
        int flag = 0;
        try {
            newsDao.updataNews(news);
            flag = 1;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return flag;
    }

    /**
     * 根据id删除新闻
     *
     * @param id
     * @return
     */
    @Override
    public int delNews(Integer id) {
        try {
            return newsDao.delNews(id);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
